package Java241127;

public class MySingleList{
    class ListNode{
        public int val;
        public ListNode next;
        public ListNode(int val){
            this.val = val;
        }
    }
    public ListNode head;
    public int listSize;
    public void createList(){
        ListNode node1 = new ListNode(12);
        ListNode node2 = new ListNode(22);
        ListNode node3 = new ListNode(32);
        ListNode node4 = new ListNode(42);
        ListNode node5 = new ListNode(52);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;

        this.head = node1;
    }
    public void display(){
        ListNode cur=head;
        while(cur !=null){
            System.out.println(cur.val+" ");
            cur = cur.next;
        }
        System.out.println();
    }
    public void addFirst(int data){
        ListNode node=new ListNode(data);
        node.next=head;
        head =node;
        listSize++;
    }
    public void remove(int key) {
        if(head == null) {
            return;
        }
        if(head.val == key) {
            head = head.next;
            listSize--;
            return;
        }
        ListNode cur = findNode(key);
        if(cur == null) {
            System.out.println("没有你要删除的数据");
            return;
        }
        ListNode del = cur.next;
        cur.next = del.next;
        listSize--;
    }
    private ListNode findNode(int key) {
        ListNode cur = head;
        while (cur.next != null) {
            if(cur.next.val == key) {
                return cur;
            }
            cur = cur.next;
        }
        return null;
    }
    public void addLast(int data) {
        ListNode node = new ListNode(data);
        //表示链表为空
        if(head == null) {
            head = node;
            listSize++;
            return;
        }
        //找到链表的尾巴
        ListNode cur = head;
        while (cur.next != null) {
            cur = cur.next;
        }
        cur.next = node;
        listSize++;
    }
}
class Test{
    public static void main(String[] args) {
        MySingleList mySingleList = new MySingleList();
        mySingleList.addLast(12);
        mySingleList.addLast(23);
        mySingleList.addLast(34);
        mySingleList.addLast(45);
        mySingleList.display();
        mySingleList.remove(45);
        mySingleList.display();
    }
}
